<template>
  <div class="weekly-task">
    <e-container class="search-area">
      <div style="display: flex">
        <SearchInput searchText="BU">
          <a-select
            v-model:value="bu"
            show-search
            option-filter-prop="label"
            option-label-prop="label"
            :get-popup-container="triggerNode => triggerNode.parentNode"
            @change="handleBuChange"
          >
            <a-select-option v-for="item in buList" :key="item.id" :label="item.name">{{ item.name }}</a-select-option>
          </a-select>
        </SearchInput>
      </div>
    </e-container>
    <e-container style="margin-top: 24px">
      <a-spin :spinning="loading" tip="Loading...">
        <a-table
          :columns="columns"
          :data-source="data"
          class="ant-table-striped"
          :pagination="false"
          :row-class-name="(_record, index) => (index % 2 === 0 ? 'table-striped' : null)"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'operate' && hasEditPermission">
              <span style="cursor: pointer; margin-right: 36px" @click="handleEdit(record)">
                <e-icon type="edit" color="#3c6cfe" font-size="12px" /><span style="color: #3c6cfe; margin-left: 2px"
                  >Edit</span
                >
              </span>
            </template>
          </template>
          <template #emptyText>
            <e-empty />
          </template>
        </a-table>
      </a-spin>
    </e-container>

    <a-modal
      v-model:visible="visible"
      title="Weekly Task Set"
      wrap-class-name="primary-modal"
      width="888px"
      @cancel="handleCancel"
    >
      <div class="person">
        <e-icon type="SalesPersonnel" color="#818d9f" font-size="22px" />
        <span class="name">{{ currentEdit.displayName }}</span>
      </div>
      <a-form ref="formRef" :model="currentEdit" layout="vertical" :rules="rules">
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="Touched Clients" name="touchedClients">
              <e-input-number v-model:inputValue="currentEdit.touchedClients" :isAddonShow="false" :precision="2" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="Responsive Clients" name="responsiveClients">
              <e-input-number v-model:inputValue="currentEdit.responsiveClients" :isAddonShow="false" :precision="2" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="Positive Clients" name="positiveClients">
              <e-input-number v-model:inputValue="currentEdit.positiveClients" :isAddonShow="false" :precision="2" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="Phase 3" name="phase3">
              <e-input-number v-model:inputValue="currentEdit.pThree" :isAddonShow="false" :precision="2" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="Phase 2" name="phase2">
              <e-input-number v-model:inputValue="currentEdit.pTwo" :isAddonShow="false" :precision="2" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="Phase 1" name="phase1">
              <e-input-number v-model:inputValue="currentEdit.pOne" :isAddonShow="false" :precision="2" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="Close Clients" name="closeClients">
              <e-input-number v-model:inputValue="currentEdit.closeClients" :isAddonShow="false" :precision="2" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="生效执行日期" name="date">
              <e-radio v-model="currentEdit.date" :options="options" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <template #footer>
        <a-button key="back" @click="handleCancel">Cancel</a-button>
        <a-button key="submit" type="primary" @click="handleSave">Save</a-button>
      </template>
    </a-modal>
    <a-modal
      v-model:visible="noticeVisible"
      title="Tips"
      wrap-class-name="primary-modal"
      width="500px"
      @cancel="handleCancel"
    >
      <div class="tips" style="padding-top: 40px">Succeeded!</div>
      <div class="tips">The new standard will come into effect next month!</div>
      <template #footer>
        <a-button key="submit" type="primary" @click="handleSure">Sure</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, inject } from 'vue'
import { useStore } from 'vuex'
import sp from '@/api/salesPlan.js'
import pageColumns from '@/assets/script/page_columns.js'
import EContainer from '@/components/EContainer.vue'
import EEmpty from '@/components/EEmpty.vue'
import EIcon from '@/components/EIcon.vue'
import ERadio from '@/components/ERadio.vue'
import EInputNumber from '@/components/EInputNumber.vue'
import SearchInput from '../../components/SearchInput.vue'
import { SAVED_SUCCESSFULLY } from '@/constants/message.js'
const { message } = inject('Feedback')
// 有编辑权限（BUM）
const hasEditPermission = computed(() => store.getters['user/isBUM'])
const store = useStore()
// 列
const columns = reactive(pageColumns.weeklyTask)
// 列表数据
const data = ref()
// 当前编辑行数据
const currentEdit = ref({})
// 模态框是否显示
const visible = ref(false)
// 提示模态框是否显示
const noticeVisible = ref(false)
// BU
const bu = ref()
const buList = ref([])
const loading = ref(false)
const gutter = [120, 16]
const formRef = ref(null)
const rules = {
  date: [
    {
      required: true,
      message: '请选择生效执行日期.'
    }
  ]
}
const options = [
  { text: '从本月开始生效', value: 0 },
  { text: '从下月开始生效', value: 1 }
]
/**
 * 获取BU
 */
const getBu = () => {
  sp.getSalesBu()
    .then(res => {
      if (res.code === 2000) {
        buList.value = res.data
        bu.value = buList.value[0].id
      }
    })
    .then(() => {
      getList()
    })
}
/**
 * 修改BU
 * @param val
 */
const handleBuChange = val => {
  bu.value = val
  getList()
}
/**
 * 获取列表
 */
const getList = () => {
  loading.value = true
  sp.getSalesMeasureStandard({
    bu: bu.value
  })
    .then(res => {
      const num = res.data.length / 7
      const arr = []
      for (let i = 0; i < num; i++) {
        const obj = {}
        obj.measureID0 = res.data[7 * i].measureID
        obj.measureID1 = res.data[7 * i + 1].measureID
        obj.measureID2 = res.data[7 * i + 2].measureID
        obj.measureID3 = res.data[7 * i + 3].measureID
        obj.measureID4 = res.data[7 * i + 4].measureID
        obj.measureID5 = res.data[7 * i + 5].measureID
        obj.measureID6 = res.data[7 * i + 6].measureID
        obj.empID = res.data[7 * i].empID
        obj.buid = res.data[7 * i].buid
        obj.displayName = res.data[7 * i].displayName
        obj.touchedClients = res.data[7 * i].weekStandard
        obj.responsiveClients = res.data[7 * i + 1].weekStandard
        obj.positiveClients = res.data[7 * i + 2].weekStandard
        obj.pThree = res.data[7 * i + 3].weekStandard
        obj.pTwo = res.data[7 * i + 4].weekStandard
        obj.pOne = res.data[7 * i + 5].weekStandard
        obj.closeClients = res.data[7 * i + 6].weekStandard
        arr.push(obj)
      }
      data.value = arr
    })
    .finally(() => {
      setTimeout(() => {
        loading.value = false
      }, 30)
    })
}
/**
 * 编辑
 * @param record
 */
const handleEdit = record => {
  currentEdit.value = JSON.parse(JSON.stringify(record))
  sp.getSalesMeasureStandardById({
    bu: record.buid,
    empID: record.empID
  }).then(res => {
    if (res.code === 2000) {
      visible.value = true
      currentEdit.value.touchedClients = res.data[0].weekStandard
      currentEdit.value.responsiveClients = res.data[1].weekStandard
      currentEdit.value.positiveClients = res.data[2].weekStandard
      currentEdit.value.pThree = res.data[3].weekStandard
      currentEdit.value.pTwo = res.data[4].weekStandard
      currentEdit.value.pOne = res.data[5].weekStandard
      currentEdit.value.closeClients = res.data[6].weekStandard
      currentEdit.value.date = ''
    }
  })
}
/**
 * 保存数据
 */
const handleSave = () => {
  const arr = []
  for (let i = 0; i < 7; i++) {
    const obj = {}
    obj.empID = currentEdit.value.empID
    obj.measureID = currentEdit.value['measureID' + i]
    if (i === 0) {
      obj.weekStandard = Number(currentEdit.value.touchedClients)
    } else if (i === 1) {
      obj.weekStandard = Number(currentEdit.value.responsiveClients)
    } else if (i === 2) {
      obj.weekStandard = Number(currentEdit.value.positiveClients)
    } else if (i === 3) {
      obj.weekStandard = Number(currentEdit.value.pThree)
    } else if (i === 4) {
      obj.weekStandard = Number(currentEdit.value.pTwo)
    } else if (i === 5) {
      obj.weekStandard = Number(currentEdit.value.pOne)
    } else if (i === 6) {
      obj.weekStandard = Number(currentEdit.value.closeClients)
    }
    obj.buid = bu.value
    arr.push(obj)
  }
  const isCurrentMonthEffect = currentEdit.value.date === 0
  const resObj = {
    isCurrentMonthEffect,
    setSalesMeasureEmp: arr
  }
  formRef.value
    .validate()
    .then(() => {
      sp.setSalesMeasureStandard(resObj).then(res => {
        if (res.code === 2000) {
          visible.value = false
          message.success(SAVED_SUCCESSFULLY)
          // noticeVisible.value = true
          getList()
        }
      })
    })
    .catch(() => {})
}
/**
 * 取消模态框
 */
const handleCancel = () => {
  visible.value = false
}
/**
 * 取消提示模态框
 */
const handleSure = () => {
  noticeVisible.value = false
}
/**
 * 初始化
 */
onMounted(() => {
  getBu()
})
</script>

<style lang="less" scoped>
@import '@/assets/style/reset_form';
@import '@/assets/style/reset_table';
@import '@/assets/style/antd_custom';

.primary-modal {
  .person {
    margin-bottom: 15px;
  }
  .tips {
    text-align: center;
    font-size: 20px;
  }
  .name {
    font-weight: 700;
    color: @deep-gray;
    font-size: 16px;
    margin-left: 8px;
  }
}
:deep(.ant-input-number),
:deep(.ant-input-number-input),
:deep(.ant-input-number-disabled) {
  text-align: left !important;
  width: 100% !important;
  border-color: @border-color !important;
}
</style>
<route lang="yaml">
name: Weekly Task
path: '/sales-settings/weekly-task'
meta:
  title: Weekly Task
  sort: 4
  roles: isPrimaryCSO, isBUM
</route>
